<template>
	<div class="task-reporting">
		<zk-searcher v-model="query" :options="searchColumns" />
		<w-block class="body" title="项目信息列表" style="margin-top: 10px">
			<template #list>
				<div class="btn-list">
					<el-button class="btn-list-item" type="primary" @click="handleAdd({ 'relTemplateId': '', 'projectType': '' })">增加项目</el-button>
					<el-button class="btn-list-item" type="warning" @click="handleUpdate">修改</el-button>
					<el-button class="btn-list-item" type="success" @click="placeOnFile">归档</el-button>
				</div>
			</template>
			<zk-table
				:columns="tableColumns"
				:service="service"
				:query="query"
				use-selection
				:actions="actions"
				@onSelectionChange="onSelection"
				@doOtherAction="doActions"
			>
			</zk-table>
		</w-block>

		<w-dialog :visible.sync="visible" height="auto" :title="modalTitle">
			<el-form ref="modelForm" :model="model" label-width="100px">
				<el-row>

					<el-col :span="22">
						<el-form-item
							label="选用模版"
							prop="relTemplateId"
							:rules="[{ required: true, message: `选用模版不能为空`, trigger: 'blur' }]"
						>
							<el-select v-model="model.relTemplateId" placeholder="请选用模版" clearable :disabled="tempDisable" @change="changeTemplateVal">
								<el-option
									v-for="opt in optTemplateList"
									:key="opt.key"
									:value="opt.key"
									:label="opt.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="22">
						<el-form-item
							label="项目类型"
							prop="projectType"
							:rules="[{ required: true, message: `项目类型不能为空`, trigger: 'blur' }]"
						>
							<el-select v-model="model.projectType" placeholder="请选择项目类型" disabled clearable>
								<el-option
									v-for="opt in dictionaries.projectType"
									:key="opt.key"
									:value="opt.key"
									:label="opt.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>


					<el-col v-for="item of formColumns" :key="item.key" :span="item.span || 22">
						<el-form-item
							:label="item.label"
							:prop="item.key"
							:rules="item.required && [{ required: true, message: `请输入${item.label}`, trigger: 'blur' }]"
						>
							<zk-item-pool
								v-model="model[item.key]"
								:option="{...item, disabled:item.disabled }"
							/>
						</el-form-item>
					</el-col>

				</el-row>
			</el-form>
			<template #footer>
				<div class="flex-end">
					<el-button type="default" @click="visible=false">取 消</el-button>
					<el-button type="primary" @click="submit">保 存</el-button>
				</div>
			</template>
		</w-dialog>

		<w-dialog :visible.sync="visibleFile" height="auto" :title="modalTitle">
			<p>项目归档后将不能继续任何操作，且不可逆，是否确认归档？</p>
			<template #footer>
				<div class="flex-end">
					<el-button type="default" @click="visibleFile=false">取 消</el-button>
					<el-button type="primary" @click="saveFile">归 档</el-button>
				</div>
			</template>
		</w-dialog>

	</div>
</template>
<script>
import { mapGetters }                          from 'vuex'
import { TYPE_ENUM }                           from '@/common/zk-constants'
import { projectProcessManagement as service } from '@/services'
import SearchTableCRUDMixin                    from '@/mixins/search-table-crud-mixin'

const actions = [
	{ classname: 'primary', text: '详细信息', type: 'report' }
]
export default {
	mixins  : [SearchTableCRUDMixin],
	data() {
		return {
			// columns,
			service,
			actions,
			visibleFile    : false,//归档
			model          : {
				relTemplateId: '',
				projectType  : '',
			},
			optTemplateList: [],
			tempAdd        : null
		}
	},
	computed: {
		...mapGetters(['dictionaries']),
		tempDisable() {
			return !this.isAddModal
		},
		modalTitle() {
			return this.isAddModal ? '添加' : '编辑'
		},
		cols() {
			return [
				{ 'label': '项目类型', 'key': 'projectType', type: TYPE_ENUM.SELECT, storeKey: 'projectType', table: true, required: true, },
				{ 'label': '项目名称', 'key': 'projectName', table: true, search: true, form: true, required: true },
				{ 'label': '业主单位', 'key': 'yzDept', table: true, form: true },
				{ 'label': '选用模板', 'key': 'relTemplateName', table: true },
				{ 'label': '阶段', 'key': 'appPhase', table: true, storeKey: 'stage', required: true },
				{ 'label': '状态', 'key': 'states', table: true, storeKey: 'processState', },
				{ 'label': '启动时间', 'key': 'startTime', table: true, search: true, rangeKeys: ['startTimeFrom', 'startTimeTo'], type: TYPE_ENUM.DATE_RANGE },
				{ 'label': '结束时间', 'key': 'endTime', table: true, search: true, rangeKeys: ['endTimeFrom', 'endTimeTo'], type: TYPE_ENUM.DATE_RANGE },
				{ 'label': '创建人', 'key': 'createPerson', table: true },
				{ 'label': '创建机构', 'key': 'createOrg', table: true },
				{ 'label': '创建时间', 'key': 'createDate', table: true },
				{ 'label': '启动时间', 'key': 'startTime', form: true, type: TYPE_ENUM.DATE, required: true, disabled: !this.isAddModal },
				{ 'label': '结束时间', 'key': 'endTime', form: true, type: TYPE_ENUM.DATE, required: true, disabled: !this.isAddModal },
			]
		},
		tableColumns() {
			return this.cols.filter(e => e.table)
		},
		formColumns() {
			return this.cols.filter(e => e.form)
		},
		searchColumns() {
			return this.cols.filter(e => e.search)
		},
	},
	watch   : {
		visible(v) {
			if (!v && this.$refs.modelForm) {
				this.$refs.modelForm.resetFields()
				this.model = {
					relTemplateId: '',
					projectType  : '',
				}
				if (this.tempAdd) {
					const i = this.optTemplateList.findIndex(item => item.key == this.tempAdd.key)
					if (i > -1) {
						this.optTemplateList.splice(i, 1)
						this.tempAdd = null
					}
				}
			}
		}
	},
	methods : {
		changeTemplateVal(key) {
			const oTemp = this.optTemplateList.find(item => item.key === key)
			this.model.projectType = this.dictionaries.projectType.find(item => item.key === oTemp.project_type).key
		},
		handleUpdate(model = {}) {
			this.isAddModal = false
			if (this.selectedRows.length === 1) {
				const [selected = {}] = this.selectedRows
				if (selected.id && selected.relTemplateId) {
					this.model = { ...this.model, ...selected, ...model, template_name: this.template_name }

					const temp = this.optTemplateList.find(item => item.id === selected.relTemplateId)
					if (!temp) {
						this.tempAdd = { ...selected, key: selected.relTemplateId, value: selected.relTemplateName }
						this.optTemplateList.unshift(this.tempAdd)
						console.log(this.tempAdd);
					}

					this.visible = true
				}
			}
			else if (this.selectedRows.length > 1) {
				this.$message.warning('请选择唯一一条记录')
			}
			else {
				this.$message.warning('请选择要编辑的记录')
			}
		},
		doActions({ row, type }) {
			(type === 'report') && this.$router.push({
				path : `/tree-task/${ row.id }`,
				query: {
					projectName: row.projectName
				}
			})
		},
		async getTemplateList() {
			this.optTemplateList = await service.queryTemplateList_single({ is_start: '1' }) //接口返回来的时候, 已经处理了key value
		},
		placeOnFile(model = {}) {
			if (this.selectedRows.length) {
				const [selected = {}] = this.selectedRows
				if (selected.id) {
					this.model = { ...selected, ...model }
					this.visibleFile = true
				}
			}
			else {
				this.$message.warning('请选择要归案的记录')
			}
		},
		async saveFile() {
			// console.log(this.model);
			if (this.model.endTime) {
				const result = await service.doProjectCommit({ "id": this.model.id })
				// console.log('saveFile', result);
				if (result.code === 0) {
					this.$message.success(`项目归案成功!`)
					this.visibleFile = false;
					this.reload();
				}
			}
			else {
				this.$message.warning(`项目必须有结束时间`)
			}
		}
	},
	mounted() {
		this.getTemplateList()
	}
}
</script>
<style scoped lang="scss">
</style>

